<template>
	<div class="container">
		<Breadcrumb/>
		<a-card class="data-card ">
			<a-row>
				<a-col :flex="1">
					<a-form :model="formModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
						<a-row :gutter="20">
							<a-col :span="5">
								<a-form-item field="username" label="用户名">
									<a-input v-model="formModel.username" placeholder="请输入用户名" allow-clear />
								</a-form-item>
							</a-col>
							<a-col :span="5">
								<a-form-item field="nickname" label="姓名">
									<a-input v-model="formModel.nickname" placeholder="请输入姓名" allow-clear />
								</a-form-item>
							</a-col>
							<a-col :span="5">
								<a-form-item field="sex" label="性别">
									<a-select v-model="formModel.sex" :options="sexs" placeholder="请选择性别" allow-clear />
								</a-form-item>
							</a-col>
							<a-col :span="5">
								<a-form-item field="deptId" label="部门">
									<a-cascader v-model='formModel.deptId' check-strictly :options='depts' placeholder="请选择所在部门" :field-names='props' :show-all-levels='false' allow-clear></a-cascader>
								</a-form-item>
							</a-col>
							<a-col :span="5">
								<a-form-item field="isLocking" label="锁定状态">
									<a-select v-model="formModel.isLocking" :options="isLockings" placeholder="请选择锁定状态" allow-clear />
								</a-form-item>
							</a-col>
							<a-col :span="5">
								<a-space :size="18">
									<a-button type="primary" @click="onPageChange(1)">
										<template #icon>
											<icon-search />
										</template>
										搜索
									</a-button>
									<a-button @click="reset">
										<template #icon>
											<icon-refresh />
										</template>
										重置
									</a-button>
								</a-space>
							</a-col>
						</a-row>
					</a-form>
				</a-col>
			</a-row>
			<a-divider style="margin-top: 0" />
			<a-row style="margin-bottom: 16px">
				<a-col :span="12">
					<a-space>
						<a-button @click="openAdd" type="primary">
							<template #icon>
								<icon-plus />
							</template>
							新增
						</a-button>
						<a-button @click="openUpload">
							批量导入
						</a-button>
					</a-space>
				</a-col>
				<a-col :span="12" style="display: flex; align-items: center; justify-content: end">
					<a-space>
						<a-button @click='openUnlockAll()' type="primary" status="success" :disabled='!userIds || userIds.length<=0'>
							批量解锁
						</a-button>
						<a-button @click='downloadUser'>
							<template #icon>
								<icon-download />
							</template>
							批量导出
						</a-button>
					</a-space>
				</a-col>
			</a-row>
			<a-table ref="userList" row-key="userId" v-model:selectedKeys="userIds" :loading="loading" page-position='bottom' :pagination="pagination" :row-selection="rowSelection" :columns="columns" :data="renderData" :bordered="false" @page-change="onPageChange" @page-size-change="onPageSizeChange">
				<template #sex="{ record }">
					<template v-for="(item, index) in sexs">
						<span v-if='record.sex == item.value'>{{ item.label }}</span>
					</template>
				</template>
				<template #isLocking="{ record }">
					<template v-for="(item, index) in isLockings">
						<span v-if='record.isLocking == item.value'>{{ item.label }}</span>
					</template>
				</template>
				<template #option="{ record }">
					<a-space :size="18">
						<a-button type="outline" @click='openRePass(record)'>
							重置密码
						</a-button>
						<a-button @click='openUnlock(record)' type="primary" status="success" v-if="record.isLocking == '1'">
							解锁
						</a-button>
						<a-button @click='openEdit(record)' type="primary">
							编辑
						</a-button>
						<a-button status="danger" @click='openDelete(record)' v-if="record.username != 'admin' ">
							删除
						</a-button>
					</a-space>
				</template>
			</a-table>
		</a-card>
		<a-modal v-model:visible="addShow" @cancel="handleCancel" :on-before-ok="handleCheck" :mask-closable='false' unmountOnClose width="900px">
			<template #title>
				用户
			</template>
			<a-form ref="addModel" :rules="rules" :model="addForm">
				<a-row style="margin-bottom: 16px">
					<a-col :span="12">
						<a-form-item field="username" label="用户名">
							<a-input v-model="addForm.username" size='large' placeholder="请输入用户名" :disabled='addForm.userId?true:false' />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="nickname" label="姓名">
							<a-input v-model="addForm.nickname" size='large' placeholder="请输入姓名" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="sex" label="性别">
							<a-select v-model="addForm.sex" :options="sexs" placeholder="请选择性别" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="mobile" label="手机号">
							<a-input v-model="addForm.mobile" size='large' placeholder="请输入手机号" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="deptId" label="部门">
							<a-cascader v-model='addForm.deptId' check-strictly :options='depts' placeholder="请选择所在部门" :field-names='props' :show-all-levels='false'></a-cascader>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="effectiveTime" label="有效期">
							<a-date-picker v-model="addForm.effectiveTime" size='large' placeholder="请选择有效期" style='width: 100%;' :allow-clear='false' />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="roleId" label="角色">
							<a-select v-model="addForm.roleId" :options="roles" :field-names="rolesFields" placeholder="请选择性别" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="organizationList" label="管理班级">
							<a-cascader v-model='addForm.organizationList' :max-tag-count='1' :options='organizations' multiple placeholder="请选择班级" :field-names='organizationsFields'></a-cascader>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item field="majorIds" label="专业">
							<a-select v-model="addForm.majorIdsArr" @change='majorChange' :options="majors" :max-tag-count='1' :field-names="majorsFields" multiple placeholder="请选择专业" />
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-modal>
		<a-modal v-model:visible="uploadShow" @cancel="uploadCancel" :on-before-ok="uploadCheck" :mask-closable='false' unmountOnClose width="450px">
			<template #title>
				导入用户
			</template>
			<a-form ref="uploadModel" :rules="uploadRules" :model="uploadForm">
				<a-row style="margin-bottom: 16px">
					<a-form-item field="deptId" label="部门">
						<a-cascader v-model='uploadForm.deptId' check-strictly :options='depts' placeholder="请选择所在部门" :field-names='props' :show-all-levels='false'></a-cascader>
					</a-form-item>
					<a-form-item field="effectiveTime" label="有效期">
						<a-date-picker v-model="uploadForm.effectiveTime" size='large' placeholder="请选择有效期" style='width: 100%;' :allow-clear='false' />
					</a-form-item>
					<a-form-item field="roleId" label="角色">
						<a-select v-model="uploadForm.roleId" :options="roles" :field-names="rolesFields" placeholder="请选择性别" />
					</a-form-item>
					<a-form-item field="majorIds" label="专业">
						<a-select v-model="uploadForm.majorIdsArr" @change='majorUpChange' :options="majors" :field-names="majorsFields" multiple placeholder="请选择专业" />
					</a-form-item>
					<a-form-item field="file" label="文件">
						<a-upload class='upload_box' @change="onChange" accept='.xls,.xlsx' ref="uploadRef" :auto-upload="false" :limit='1'>
							<template #upload-button>
								<a-space>
									<a-button type='primary'>选择附件</a-button>
									<a-button @click.stop='downloadTemplate'>下载模板</a-button>
								</a-space>
							</template>
						</a-upload>
					</a-form-item>
				</a-row>
			</a-form>
		</a-modal>
		<a-modal v-model:visible="lockShow" @cancel="lockCancel" :on-before-ok="lockCheck" :mask-closable='false' unmountOnClose width="450px">
			<template #title>
				解锁用户
			</template>
			<a-form ref="lockModel" :rules="lockRules" :model="lockForm">
				<a-row style="margin-bottom: 16px">
					<a-form-item field="effectiveTime" label="有效期">
						<a-date-picker v-model="lockForm.effectiveTime" size='large' placeholder="请选择有效期" style='width: 100%;' :allow-clear='false' />
					</a-form-item>
				</a-row>
			</a-form>
		</a-modal>
	</div>
</template>
<script lang="ts">
	export default {
		name: 'user',
	};
</script>
<script lang="ts" setup>
	import { computed, ref, reactive, watch, nextTick } from 'vue';
	import useLoading from '@/hooks/loading';
	import { useSelectionStore } from '@/store';
	import type {
		TableColumnData
	} from '@arco-design/web-vue/es/table/interface';
	import { Message, Modal } from '@arco-design/web-vue';
	import { adminUserList, adminUserSave, adminUserUpdate, adminUserRemove, resetPassword, importAdminUser, adminUserExport, downloadTemplate, unlockUserBatch } from '@/api/adminUser.ts'
	import { deptTree } from '@/api/dept.ts'
	import { organizationTree } from '@/api/organization.ts'
	import { roleList } from '@/api/role.ts'
	import { majorTree } from '@/api/major.ts'

	const {
		loading,
		setLoading
	} = useLoading(true);

	const generateDataModel = () => {
		return {
			userId: '',
			username: '',
			nickname: '',
			sex: '',
			mobile: '',
			deptId: '',
			roleId: '',
			effectiveTime: '',
			organizationList: [],
			majorIds: '',
			majorIdsArr: [],
		};
	};

	const rules = {
		username: [{
			required: true,
			message: '请输入用户名'
		}, {
			minLength: 4,
			message: '最少输入四位'
		}],
		nickname: [{
			required: true,
			message: '请输入姓名'
		}],
		sex: [{
			required: true,
			message: '请选择性别'
		}],
		deptId: [{
			required: true,
			message: '请选择部门'
		}],
		roleId: [{
			required: true,
			message: '请选择角色'
		}],
		effectiveTime: [{
			required: true,
			message: '请选择有效期'
		}],
		organizationList: [{
			required: true,
			message: '请选择班级'
		}],
		majorIds: [{
			required: true,
			message: '请选择专业'
		}],
	};
	const addForm = ref(generateDataModel());
	const addShow = ref(false);
	const addModel = ref();

	const openAdd = () => {
		addForm.value = generateDataModel()
		addShow.value = true;
	}

	const majorChange = (majorIdsArr) => {
		if(majorIdsArr && majorIdsArr.length) {
			addForm.value.majorIds = majorIdsArr.join(',')
		} else {
			addForm.value.majorIds = ''
		}
	}

	const handleCheck = (done) => {
		if(loading.value) {
			done(false);
			return;
		}
		setLoading(true);
		setTimeout(() => {
			setLoading(false);
		}, 1500)
		addModel.value.validate(async(errors: undefined | Record < string, ValidatedError > ) => {
			if(!errors) {
				if(addForm.value.userId) {
					adminUserUpdate(addForm.value).then(res => {
						if(res.code == '200') {
							Message.success({
								content: res.message,
							});
							done(true)
							reset();
						} else {
							done(false)
						}
					})
				} else {
					adminUserSave(addForm.value).then(res => {
						if(res.code == '200') {
							Message.success({
								content: res.message,
							});
							done(true)
							reset();
						} else {
							done(false)
						}
					})
				}
			} else {
				done(false)
			}
		})
	}

	const openEdit = (item) => {
		let majorIdsArr = [];
		if(item.majorIds) {
			majorIdsArr = item.majorIds.split(',');
			majorIdsArr = majorIdsArr.map(item => {
				return +item
			})
		}
		addForm.value = Object.assign({}, item, {
			majorIdsArr: majorIdsArr
		})
		addShow.value = true;
	}

	const handleCancel = () => {
		addShow.value = false;
	}
	const openDelete = (item) => {
		Modal.confirm({
			title: '提示',
			content: '确认删除吗？',
			onOk() {
				adminUserRemove({
					userId: item.userId
				}).then(res => {
					if(res.code == '200') {
						Message.success({
							content: res.message,
						});
						fetchData();
					}
				})
			},
		})

	}
	const openRePass = (item) => {
		Modal.confirm({
			title: '提示',
			content: '确认重置此用户密码吗？',
			onOk() {
				resetPassword({
					userId: item.userId
				}).then(res => {
					if(res.code == '200') {
						Message.success({
							content: res.message,
						});
					}
				})
			},
		})
	}

	const lockRules = {
		effectiveTime: [{
			required: true,
			message: '请选择有效期'
		}],
	};
	const generateLockModel = () => {
		return {
			userIds: '',
			effectiveTime: '',
		};
	};
	const lockForm = ref(generateLockModel());

	const lockShow = ref(false);
	const lockModel = ref();
	const userIds = ref([]);

	const openUnlock = (item) => {
		lockForm.value = {
			...generateLockModel(),
			userIds: item.userId,
		}
		lockShow.value = true;
	}

	const openUnlockAll = () => {
		lockForm.value = {
			...generateLockModel(),
			userIds: userIds.value.join(','),
		}
		lockShow.value = true;
	}

	const lockCheck = (done) => {
		if(loading.value) {
			done(false);
			return;
		}
		setLoading(true);
		setTimeout(() => {
			setLoading(false);
		}, 1500)
		lockModel.value.validate(async(errors: undefined | Record < string, ValidatedError > ) => {
			if(!errors) {
				unlockUserBatch(lockForm.value).then(res => {
					if(res.code == '200') {
						done(true)
						reset();
						Message.success({
							content: res.message,
						});
					} else {
						done(false)
					}
				})
			} else {
				done(false)
			}
		})
	}
	const lockCancel = () => {
		lockShow.value = false;
	}

	const generateUploadModel = () => {
		return {
			file: null,
			deptId: '',
			roleId: '',
			effectiveTime: '',
			majorIds: '',
			majorIdsArr: [],
		};
	};

	const uploadRules = {
		deptId: [{
			required: true,
			message: '请选择部门'
		}],
		roleId: [{
			required: true,
			message: '请选择角色'
		}],
		effectiveTime: [{
			required: true,
			message: '请选择有效期'
		}],
		majorIds: [{
			required: true,
			message: '请选择专业'
		}],
		file: [{
			required: true,
			message: '请选择附件'
		}],
	};
	const uploadForm = ref(generateUploadModel());
	const uploadShow = ref(false);
	const uploadModel = ref();
	const openUpload = () => {
		uploadForm.value = generateDataModel()
		uploadShow.value = true;
	}

	const majorUpChange = (majorIdsArr) => {
		if(majorIdsArr && majorIdsArr.length) {
			uploadForm.value.majorIds = majorIdsArr.join(',')
		} else {
			uploadForm.value.majorIds = ''
		}
	}
	const onChange = (fileList) => {
		if(fileList && fileList.length > 0) {
			uploadForm.value.file = fileList[0].file
		} else {
			uploadForm.value.file = null
		}
	};

	const uploadCheck = (done) => {
		if(loading.value) {
			done(false);
			return;
		}
		setLoading(true);
		setTimeout(() => {
			setLoading(false);
		}, 1500)
		uploadModel.value.validate(async(errors: undefined | Record < string, ValidatedError > ) => {
			if(!errors) {
				let formData = new FormData();
				formData.append("deptId", uploadForm.value.deptId);
				formData.append("roleId", uploadForm.value.roleId);
				formData.append("effectiveTime", uploadForm.value.effectiveTime);
				formData.append("majorIds", uploadForm.value.majorIds);
				formData.append("file", uploadForm.value.file);
				importAdminUser(formData).then(res => {
					if(res.code == '200') {
						Message.success({
							content: res.message,
						});
						reset()
						done(true)
					} else {
						done(false)
					}
				})
			} else {
				done(false)
			}
		})
	}
	const uploadCancel = () => {
		uploadShow.value = false;
	}

	const rowSelection = reactive({
		type: 'checkbox',
		showCheckedAll: true,
		onlyCurrent: false,
	});
	const columns = computed < TableColumnData[] > (() => [{
			title: '用户名',
			dataIndex: 'username',
		},
		{
			title: '姓名',
			dataIndex: 'nickname',
		},
		{
			title: '性别',
			dataIndex: 'sex',
			slotName: 'sex',
			align: 'center'
		},
		{
			title: '部门',
			dataIndex: 'deptName',
		},
		{
			title: '角色',
			dataIndex: 'roleName',
			align: 'center'
		},
		{
			title: '锁定状态',
			dataIndex: 'isLocking',
			slotName: 'isLocking',
			align: 'center'
		},
		{
			title: '有效期',
			dataIndex: 'effectiveTime',
			align: 'center'
		},
		{
			title: '操作',
			dataIndex: 'option',
			slotName: 'option',
			align: 'center'
		},
	]);
	
	const isLockings = useSelectionStore().isLockings;
	const sexs = useSelectionStore().sexs;

	const generateFormModel = () => {
		return {
			username: '',
			nickname: '',
			deptId: '',
			sex: '',
			isLocking: '',
		};
	};

	const formModel = ref(generateFormModel());
	const renderData = ref([]);
	const userList = ref();

	const basePagination: Pagination = {
		current: 1,
		pageSize: 10,
		total: 0

	};
	const pagination = reactive({
		...basePagination,
		'hide-on-single-page': true,
		'show-total': true,
		'show-jumper': true,
		'show-page-size': true,
	});

	const fetchData = async() => {
		setLoading(true);
		try {
			const data = {
				pageNum: pagination.current,
				...pagination,
				...formModel.value,
			}
			adminUserList(data).then(res => {
				let list = res.data.list || [];
				list.map(item => {
					item.disabled = item.isLocking == 1 ? false : true
				})
				renderData.value = list;
				pagination.total = res.data.total;
				pagination.current = res.data.current;

				userList.value.selectAll(false)
			})
		} catch(err) {
			console.log(err)
		} finally {
			setLoading(false);
		}
	};

	const onPageChange = (current: number) => {
		pagination.current = current;
		fetchData();
	};
	const onPageSizeChange = (pageSize: number) => {
		pagination.pageSize = pageSize;
		fetchData();
	};

	const reset = () => {
		formModel.value = generateFormModel();
		fetchData()
	};
	fetchData();

	const downloadUser = () => {
		adminUserExport(formModel.value).then(res => {})
	}

	const depts = ref([]);
	const props = {
		value: 'id',
		label: 'name'
	}
	const getDepts = () => {
		deptTree().then(res => {
			depts.value = res.data || []
		})
	}
	getDepts()

	const roles = ref([]);
	const rolesFields = {
		value: 'roleId',
		label: 'roleName'
	}
	const getRoles = () => {
		roleList().then(res => {
			roles.value = res.data || []
		})
	}
	getRoles()

	const organizations = ref([]);
	const organizationsFields = {
		value: 'id',
		label: 'name'
	}
	const getOrganizations = () => {
		organizationTree().then(res => {
			organizations.value = res.data || []
		})
	}
	getOrganizations()

	const majors = ref([]);
	const majorsFields = {
		value: 'id',
		label: 'name'
	}
	const getMajors = () => {
		majorTree().then(res => {
			majors.value = res.data || []
		})
	}
	getMajors()
</script>